<template>
  <div class="add-or-edit-product factory-container">
    <header class="mb20 pd20 header-wrap">
      <div>
        <template v-if="stepsActive === 1 || stepsActive === 2">
          <el-button
            type="primary"
            plain
            :icon="Tickets"
            @click="clickSave(1)"
            v-if="actionType === 'add' || actionType === 'copy' || editDetailInfo.businessProductStatus === 1"
          >
            保存预发布
          </el-button>
          <el-button type="primary" plain :icon="Search" @click="clickSave(1, 'review')">保存并预览商品</el-button>
          <el-button type="primary" :icon="Upload" @click="clickSave(2)">发布商品</el-button>
        </template>
      </div>
      <!-- <el-button @click="toPath">返回上一页</el-button> -->
      <el-button @click="back" v-if="isShowBack || $route.query?.showBack === 'true'">返回上一页</el-button>
    </header>
    <!-- <div class="line"></div> -->
    <!-- 步骤条 -->
    <!-- <el-button style="margin-top: 12px" @click="preStep">上一步</el-button>
    <el-button style="margin-top: 12px" @click="nextStep">下一步</el-button> -->
    <el-steps class="mt66" style="max-width: 100%" :active="stepsActive" finish-status="success">
      <el-step title="选择发布类目" @click="changeSteps(0)"> </el-step>
      <el-step title="编辑商品信息" @click="changeSteps(1)" />
      <el-step title="提交商品发布" @click="changeSteps(2)" />
    </el-steps>

    <div class="steps1" v-show="stepsActive === 0">
      <!-- 第一步 -->
      <p class="f18 mb24">选择商品类目</p>
      <el-form :model="form" ref="formRef" label-width="auto" :rules="rules" style="width: 100%">
        <el-form-item label="商品分类" prop="categoryId">
          <el-tree-select
            :disabled="JSON.stringify(editDetailInfo) !== '{}'"
            ref="treeSelectRef"
            v-model="form.categoryId"
            node-key="categoryId"
            default-expand-all
            :data="products"
            :check-strictly="false"
            :render-after-expand="false"
            :props="{
              label: 'name',
              value: 'categoryId'
            }"
          />
          <!-- @node-click="handleNodeClick" -->
        </el-form-item>
        <el-form-item label="">
          <el-checkbox v-model="form.agree" size="large">
            我已阅读如下规则<el-button link type="primary" @click="dialogVisibleAgree = true">平台规则</el-button>
          </el-checkbox>
        </el-form-item>
      </el-form>
      <div class="btn-wrap">
        <el-button type="default" @click="toPath">返回</el-button>
        <el-button type="primary" @click="nextStep(1)">下一步</el-button>
      </div>
    </div>
    <div class="steps2" v-show="stepsActive === 1">
      <baseinfo ref="baseinfoRef" :optionInfo="optionInfo" :Enums="Enums" :categoryId="form.categoryId"></baseinfo>
      <div class="block mb40"></div>
      <attr
        ref="attrRef"
        :optionInfo="optionInfo"
        :Enums="Enums"
        :Provides="Provides"
        :categoryId="form.categoryId"
        @getAttrValueBack="getAttrValue"
      ></attr>
      <div class="block mb40"></div>
      <sku ref="skuRef" :optionInfo="optionInfo" :Enums="Enums" :categoryId="form.categoryId" :attrValue="attrValue"></sku>
      <div class="block mb40"></div>
      <editor :optionInfo="optionInfo" ref="editorRef"></editor>
      <!-- <div class="btn-wrap mt20 fixed-btn">
        <el-button type="primary" @click="nextStep(2)">下一步</el-button>
      </div> -->
    </div>
    <div class="steps3" v-show="stepsActive === 2">
      <div class="mt44" style="text-align: center">
        <el-button
          v-if="actionType === 'add' || actionType === 'copy' || editDetailInfo.businessProductStatus === 1"
          type="primary"
          @click="reportPoducts(1)"
        >
          保存预发布
        </el-button>
        <el-button type="primary" @click="reportPoducts(2)">发布商品</el-button>
      </div>
    </div>

    <!-- 平台规则 -->
    <el-dialog v-model="dialogVisibleAgree" title="平台规则" width="60%">
      <div v-html="agreementHtml"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Delete, Edit, Search, Share, Upload, Tickets } from "@element-plus/icons-vue";
import baseinfo from "./components/baseinfo.vue";
import attr from "./components/attr.vue";
import sku from "./components/sku.vue";
import editor from "./components/editor.vue";
import {
  getcategoryList2,
  getAgreementList,
  getEnumAll,
  getDictList,
  getProvideList,
  getSuppliers,
  saveProduct,
  getProductDetail,
  eidtProduct,
  getCopyDetail
} from "@/apis/products/specifications";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import { microAppMainRouter } from "@/microApp";

const isShowBack = ref(true);
const stepsActive = ref(0);
const form = ref({ categoryId: "", agree: true });
const formRef = ref();
const rules = ref({
  categoryId: [{ required: true, message: "请选择商品分类", trigger: ["blur", "change"] }]
});
const products = ref([]);
const agreementHtml = ref(""); //协议内容
const dialogVisibleAgree = ref(false);
const Enums = ref([]);
const Provides = ref([]);
const baseinfoRef = ref();
const attrRef = ref();
const skuRef = ref();
const editorRef = ref();
const actionType = ref("add");
const collectId = ref("");
const redirect = ref("");
const editDetailInfo = ref({}); //编辑时，当前的商品详情
const optionInfo = ref({
  actionType: "add",
  editDetailInfo: {}
});

onMounted(async () => {
  collectId.value = route.query.collectId;
  redirect.value = route.query.redirect;
  if (collectId.value) {
    console.log("route====", route);
    if (route.name.includes("edit")) {
      actionType.value = "edit";
      stepsActive.value = 1;
      isShowBack.value = false;
    } else if (route.name.includes("copy")) {
      actionType.value = "copy";
      stepsActive.value = 1;
      isShowBack.value = false;
    } else if (route.name.includes("re-applay")) {
      actionType.value = "re-applay";
      stepsActive.value = 1;
      isShowBack.value = false;
    }
  }
  console.log("操作类型===", actionType.value, "collectId===", collectId.value);

  getProducts();
  getAgreement();

  const _Enums = await getEnumAll(); //查询完整的数据字典
  const _zhEnums = await getDictList(); //查询租户的数据字典
  // console.log("这是租户的数据字典===", _Enums.data, _zhEnums.data);
  Enums.value = [..._Enums.data, ..._zhEnums.data];

  const _Provides = await getSuppliers();
  Provides.value = _Provides.data;
  // console.log("工厂列表===", _Provides.data.list);

  if (actionType.value !== "add") {
    if (actionType.value === "copy") {
      getCopyDetail({ collectId: collectId.value }).then(res => {
        if (res.code === 200) {
          console.log("复制商品详情===", res.data);
          form.value.categoryId = res.data.categoryId;
          editDetailInfo.value = res.data;
          optionInfo.value = {
            actionType: actionType.value,
            editDetailInfo: editDetailInfo.value
          };
        }
      });
    } else {
      getProductDetail({ collectId: collectId.value }).then(res => {
        if (res.code === 200) {
          console.log("商品详情===", res.data);
          form.value.categoryId = res.data.categoryId;
          editDetailInfo.value = res.data;
          optionInfo.value = {
            actionType: actionType.value,
            editDetailInfo: editDetailInfo.value
          };
        }
      });
    }
  }
});

//从attr组件更改属性值时，获取到的最新属性值数组
const attrValue = ref([]);
const getAttrValue = arr => {
  // console.log("这是更改后的属性值", arr);
  attrValue.value = arr;
};

const clickSave = async (type, review = false) => {
  // type 1-预发布 2-保存并发布
  //下一步，进行校验
  const flag = await nextStep(2, false);
  flag && type === 1 ? reportPoducts(1, review) : type === 2 ? reportPoducts(2, review) : "";
};

const back = () => {
  if (redirect.value) {
    const query = route.query;
    delete query.redirect;
    delete query.showBack;
    router.push({ path: redirect.value, query: query });
  }
};

const getAgreement = () => {
  getAgreementList().then(res => {
    if (res.code === 200) {
      console.log("协议内容===", res);
      agreementHtml.value = res.data[0].content;
    }
  });
};

//获取商品分类tree
const getProducts = () => {
  getcategoryList2({ searchkey: "" }).then(res => {
    if (res.code === 200) {
      // console.log("这是商品分类====", res.data);
      products.value = res.data;
    }
  });
};

const changeSteps = val => {
  nextStep(val);
};
const preStep = () => {
  if (stepsActive.value-- < 0) stepsActive.value = 0;
};

const Params = ref({});
const nextStep = async (num, isNext = true) => {
  if (num === 1) {
    formRef.value.validate((valid, fields) => {
      if (valid) {
        console.log("第一步的form===", form.value);
        if (form.value.agree) {
          if (isNext) stepsActive.value = num;
        } else {
          ElMessage({
            message: "请同意平台规则！",
            type: "error"
          });
        }
      }
    });
  } else if (num === 2) {
    let flag = false;
    await Promise.all([
      baseinfoRef.value.getBaseInfo(),
      attrRef.value.getAttrForm(),
      skuRef.value.getSkuList(),
      editorRef.value.getEditor()
    ]).then(res => {
      const params = {
        ...res[0],
        ...res[1],
        specificationList: res[2].specesList,
        businessSkuList: res[2].skuList,
        isBathChangePrice: res[2].isBathChangePrice, //不批量更新调价 1-是 0-否
        shopDetail: res[3].valueHtml
      };
      Params.value = params;
      console.log("发布商品数据===", params);
      if (isNext) stepsActive.value = num;
      flag = true;
    });
    return flag;
  } else {
    if (isNext) stepsActive.value = num;
  }
};

// 路由跳转
import { ElMessage } from "element-plus";
const toPath = () => {
  router.push({
    path: "/products/manage"
  });
};

const reportPoducts = (publishStatus, review) => {
  if (actionType.value === "add" || actionType.value === "copy") {
    saveProduct({ ...Params.value, publishStatus: publishStatus }).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "发布成功！",
          type: "success"
        });
        if (review) {
          //本页签内跳转成详情页
          router.push({
            path: "/products/manage/edit",
            query: {
              collectId: res.data?.collectId,
              redirect: "/products/manage",
              showBack: true
            }
          });

          //预览
          // microAppMainRouter("replace", { path: "/designer" });
          const baseRouter = window.microApp.router.getBaseAppRouter();
          const routeUrl = baseRouter.resolve({
            path: "/designer/shopDetail/index",
            query: { id: res.data?.productId, review: true }
          });
          window.open(routeUrl.href, "_blank");
        } else {
          back();
        }
      }
    });
  } else if (actionType.value === "edit" || actionType.value === "re-applay") {
    editorRef.value.saveRichTextFun();
    const _Params = JSON.parse(JSON.stringify(Params.value));
    delete _Params.shopDetail;
    if (actionType.value === "re-applay") {
      _Params.publishStatus = 2;
    } else {
      _Params.publishStatus = publishStatus;
    }
    console.log("编辑的参数===", _Params);
    eidtProduct({ ...editDetailInfo.value, ..._Params, productId: editDetailInfo.value.productId }).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "操作成功",
          type: "success"
        });
        if (review) {
          //预览
          // microAppMainRouter("replace", { path: "/designer" });
          const baseRouter = window.microApp.router.getBaseAppRouter();
          const routeUrl = baseRouter.resolve({
            path: "/designer/shopDetail/index",
            query: { id: editDetailInfo.value.productId, review: true }
          });
          window.open(routeUrl.href, "_blank");
        } else {
          back();
        }
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.header-wrap {
  position: sticky;
  top: 0px;
  background-color: white;
  z-index: 99;
  margin: 0 -20px;
  border-bottom: 1px solid #e1effe;
}
:deep(.el-step__title) {
  cursor: pointer;
}
.btn-wrap {
  text-align: center;
}
.block {
  height: 20px;
  background-color: #f5f7fa;
  margin: 0 -20px;
}
.add-or-edit-product {
  padding-top: 0 !important;
  :deep(.el-steps) {
    padding-left: 16%;
    .el-step__icon-inner {
      font-weight: normal;
    }
    .el-step {
      position: relative;
      flex-basis: 40% !important;
      &.is-flex {
        flex-basis: 40% !important;
      }
      .el-step__head.is-success {
        border-color: transparent;
        .el-step__line {
          height: 0;
          background-color: transparent;
        }
        .el-step__icon.is-text {
          background-color: #e8f3ff;
          color: #165dff;
        }
      }
      .el-step__head.is-process {
        .el-step__icon.is-text {
          border: none;
          background-color: #165dff;
          color: white;
          .el-step__icon-inner {
            font-weight: normal;
          }
        }
      }
      .el-step__head.is-wait {
        .el-step__icon.is-text {
          border: none;
          background-color: #f2f3f5;
          color: #4e5969;
        }
      }
      .el-step__title.is-wait {
        color: #4e5969;
      }
      .el-step__main {
        position: absolute;
        top: -8px;
        left: 40px;
        .el-step__title {
          font-weight: normal;
          &.is-success {
            color: #4e5969;
          }
        }
      }
      .el-step__line-inner {
        border: none;
      }
      .el-step__line {
        left: 160px;
        right: 25px;
        height: 0px;
        background-color: transparent;
        border-bottom: 1px dashed #d8d8d8;
      }
    }
  }
  header {
    display: flex;
    justify-content: space-between;
  }
  .line {
    height: 1px;
    background-color: #e1effe;
    margin: 0 -20px;
  }
}
</style>
